let videoAd = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    category:[],
    videoCategory:[],
    pageLimit:10,
    pageVideoLimit:10,
    chooseIndex:0,
    number:0,
    path:'',
    page:1,
    type:'all',
    list:[],
    url:'https://guanhe.store/picture/',
    isBottom:false,
    chooseItem:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: getApp().globalData.jili
      })
      videoAd.onLoad(() => { })
      videoAd.onError((err) => { })
      videoAd.onClose((status) => { 
        if (status && status.isEnded || status === undefined) {
          // 正常播放结束，下发奖励
          // continue you code
          wx.showLoading({
            title: '请稍等...',
          })
          wx.downloadFile({
            url: this.data.chooseItem.path,
            success(e){
              console.log(e,'下载成功')
              wx.hideLoading({
                success: (res) => {},
              })
              wx.saveImageToPhotosAlbum({
                filePath: e.tempFilePath,
                success(e){
                  console.log(e,'保存成功')
                  that.setData({
                    ['list['+that.data.chooseItemIndex/1+'].number']:that.data.list[that.data.chooseItemIndex/1].number+1
                  })
                  let number = wx.getStorageSync('number')
                  number[that.data.type] = that.data.list.map(item=>{
                    return item.number
                  })
                  wx.setStorageSync('number', number)
                },
                fail(e){
                  console.log(e,'保存失败')
                }
              })

            },
            fail(err){
              console.log(err)
              wx.hideLoading({
                success: (res) => {},
              })
            }
          })
          console.log('已完成')
        } else {
          console.log('未完成')
        }
      })
    }
    getApp().chaping()
    let category = [{"name":"所有","path":"all","number":69},{"name":"云雾","path":"yun","number":30},{"name":"山","path":"shan","number":44},{"name":"星空","path":"xingkong","number":17},{"name":"人物","path":"renwu","number":12},{"name":"植物","path":"zhiwu","number":30}]
    that.setData({
      category,
      number:category[0].number
    })
    that.loadNumber()
  },
  onShareTimeline: function () {
    
  },
  getPicList(){
    let url = ''
    let type = this.data.type
    let that = this
    if(type == 'all'){
      url = 'https://mp.weixin.qq.com/s/W2faQu9TFSQ5VuMVNEfvJA'
    }
    if(type == 'renwu'){
      url = 'https://mp.weixin.qq.com/s?__biz=MzI1NDU0MzI5OQ==&mid=2247485223&idx=1&sn=7ddfb5dc748c2f9b30b8b1b4fa5a9b77&chksm=e9c2d38bdeb55a9da66068c49621e0864ecdc4d8a991617a4dfe87a99ef6dfc3c791746c6917#rd'
    }
    if(type == 'shan'){
      url = 'https://mp.weixin.qq.com/s?__biz=MzI1NDU0MzI5OQ==&mid=2247485256&idx=1&sn=2c379ac91661c0a2a132061f81f17c63&chksm=e9c2d3e4deb55af2abb53256bcec6e1cec345e750bd6a2701f9e633696f7b85ee116f19e9536#rd'
    }
    if(type == 'xingkong'){
      url = 'https://mp.weixin.qq.com/s?__biz=MzI1NDU0MzI5OQ==&mid=2247485270&idx=1&sn=af822f8163893caab731ddbbdcfd3be9&chksm=e9c2d3fadeb55aec192dc23997765094d2ac14873e90c43fcb00d5a0d5c175c5f23ee86a78e3#rd'
    }
    if(type == 'yun'){
      url = 'https://mp.weixin.qq.com/s?__biz=MzI1NDU0MzI5OQ==&mid=2247485297&idx=1&sn=a4e668c170528a1135fa6c1a328f632c&chksm=e9c2d3dddeb55acb9a8b525343d7579093dee5d677092b6b6906ffa84c663d9fb74a599e1e10#rd'
    }
    if(type == 'zhiwu'){
      url = 'https://mp.weixin.qq.com/s?__biz=MzI1NDU0MzI5OQ==&mid=2247485323&idx=1&sn=f761781e6d9b4a2c2155cd31a57233d9&chksm=e9c2d327deb55a31b76fee5f566e5bb0c694fd3feabd648b13f2ed093bc40606c3a4bd7c72e7#rd'
    }
    wx.request({
      url,
      success(e){
        console.log(e.data)
        let picList = e.data.match(/\<img class=\"rich_pages.*?>/g)
        picList = picList.map(item=>{
          return item.replace(/.*data\-src\=\"(.*?)\?.*/,'$1')
        })
        that.loadContent(picList)
      }
    })
  },
  downLoad(e){
    let {ind} = e.currentTarget.dataset
    wx.showLoading({
      title: '请稍等...',
      mask:true
    })
    if (videoAd) {
      this.setData({
        chooseItem:this.data.list[ind],
        chooseItemIndex:ind
      })
      videoAd.show()
        .then(() => {
          wx.hideLoading({
            success: (res) => {},
          })
        })
        .catch(() => {
          wx.hideLoading({
            success: (res) => {},
          })
          wx.showToast({
            title: '请5s后重试',
            duration:2000
          })
        })
    } else {
      wx.hideLoading({
        success: (res) => {},
      })
    }
  },
  loadContent(list){
    let number = wx.getStorageSync('number')
    let type = this.data.type
    list = list.map(item=>{
      return {path:item}
    })
    if(number[type]){
      list.forEach((item,index)=>{
        item.number = number[type][index]||0
      })
    } else {
      list.forEach((item,index)=>{
        item.number = 0
      })
    }
    number[type] = list.map(item=>{
      return item.number
    })
    this.setData({
      list
    })
    wx.setStorageSync('number', number)
  },
  // 加载下载次数
  loadNumber(){
    let number = wx.getStorageSync('number')
    if(number){
      
    } else {
      let category = this.data.category
      number = {}
      category.forEach((item,index)=>{
        let arr = []
        let number1 = item.number
        for(let i=0;i<number1;i++){
          arr.push(0)
        }
        number[item.path] = arr
      })
      wx.setStorageSync('number', number)
    }
    // this.loadContent()
    this.getPicList()
  },
  chooseCategory(e){
    let {ind} = e.currentTarget.dataset
    if(ind == this.data.chooseIndex){return}
    this.setData({
      isBottom:false,
      chooseIndex:ind,
      page:1,
      list:[],
      type:this.data.category[ind].path,
      number:this.data.category[ind].number
    })
    this.getPicList()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // if(this.data.isBottom)return
    // this.setData({
    //   page:this.data.page+1
    // })
    // this.loadContent()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})